<!-- 优惠券管理 -->
<template>
  <div>
    <el-header>
      <el-space wrap>
        <el-input
          style="width: 190px"
          v-model.trim="configReq.title"
          clearable
          placeholder="请输入优惠券标题"
        />
        <el-select v-model="configReq.type" clearable placeholder="请选择优惠券类型">
          <el-option
            v-for="item in options.type"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select v-model="configReq.status" clearable placeholder="请选择优惠券状态">
          <el-option
            v-for="item in options.status"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button type="primary" :icon="Search" @click="getInfo">查找</el-button>
        <el-button
          type="primary"
          :icon="Plus"
          @click="
            () => {
              resetAddData();
              disabled = false;
              title = '创建';
              dialogShow = true;
            }
          "
          >添加</el-button
        >
        <el-button type="primary" :icon="Download" @click="exportExcel('#exportTab')"
          >当前页导出</el-button
        >
      </el-space>
    </el-header>
    <el-container>
      <!-- 列表 -->
      <el-table
        id="exportTab"
        :data="infoList"
        border
        align="center"
        :default-sort="{ prop: 'id', order: 'descending' }"
      >
        <el-table-column prop="id" sortable label="优惠券ID" align="center" width="90" />
        <el-table-column prop="title" label="优惠券名称" align="center" />
        <el-table-column label="优惠券类型" align="center" width="100">
          <template #default="scope">
            <el-tag>{{ scope.row.type == 1 ? "满减券" : "立减券" }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="介绍" width="120" align="center" />
        <el-table-column prop="total" label="优惠券数量" align="center" />
        <el-table-column prop="surplus" label="剩余数量" align="center" />
        <el-table-column prop="limit" label="每人限领" align="center" />
        <el-table-column label="满减金额" align="center" width="100">
          <template #default="scope"> 减免{{ scope.row.discount }}元 </template>
        </el-table-column>
        <el-table-column label="最低消费" align="center" width="130">
          <template #default="scope"> 满{{ scope.row.min }}元可用 </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status == 1 ? '' : 'danger'">{{
              switchDetails(scope.row.status)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="使用类目名称" align="center" width="110">
          <template #default="scope">
            <el-tag>{{
              scope.row.categoryTitle ? scope.row.categoryTitle : "全部类目"
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="categoryId" label="使用类目ID" align="center" />
        <el-table-column label="领券相对天数" align="center">
          <template #default="scope">
            {{ scope.row.days || "无" }}
          </template>
        </el-table-column>
        <el-table-column label="领券开始时间" align="center">
          <template #default="scope">
            {{
              scope.row.gmtStart
                ? new Date(scope.row.gmtStart).formate("yyyy-MM-dd hh:mm")
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column label="领券结束时间" align="center">
          <template #default="scope">
            {{
              scope.row.gmtEnd
                ? new Date(scope.row.gmtEnd).formate("yyyy-MM-dd hh:mm")
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="操作" align="center" width="200">
          <template #default="scope">
            <el-button type="primary" @click="changeStatus(scope.row)">{{
              switchHandle(scope.row.status)
            }}</el-button>
            <el-button type="info" @click="lookInfo(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 弹出框 -->
      <el-dialog v-model="dialogShow" :title="title" width="750px" destroy-on-close>
        <el-form
          ref="formRef"
          :disabled="disabled"
          :model="addData"
          :rules="rules"
          label-width="120px"
          status-icon
        >
          <el-form-item label="优惠券名称" prop="title">
            <el-input v-model.trim="addData.title" type="text" />
          </el-form-item>
          <el-form-item label="优惠券类型" prop="type">
            <el-select v-model="addData.type" placeholder="请选择优惠券类型">
              <el-option
                v-for="item in options.type.slice(0, 2)"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="介绍" prop="description">
            <el-input v-model="addData.description" type="text" />
          </el-form-item>
          <el-form-item label="优惠券数量" prop="total">
            <el-input
              v-model="addData.total"
              type="text"
              oninput="value=value.replace(/[^\d]/g,'')"
              maxlength="7"
            >
              <template #append>张</template>
            </el-input>
          </el-form-item>
          <el-form-item label="每人限领" prop="limit">
            <el-input
              v-model="addData.limit"
              type="text"
              oninput="value=value.replace(/[^\d]/g,'')"
              maxlength="7"
            >
              <template #append>张</template>
            </el-input>
          </el-form-item>
          <el-form-item label="优惠金额" prop="discount">
            <el-input
              v-model="addData.discount"
              type="text"
              oninput="value=value.replace(/[^\d.\d]/g,'')"
              maxlength="7"
            >
              <template #append>元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="最低消费" prop="min">
            <el-input
              v-model="addData.min"
              type="text"
              oninput="value=value.replace(/[^\d.\d]/g,'')"
              maxlength="7"
            >
              <template #append>元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="优惠券状态" prop="status">
            <el-select v-model="addData.status" placeholder="请选择优惠券状态">
              <el-option
                v-for="item in options.status.slice(0, addData.status == -1 ? 3 : 2)"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="有效期">
            <el-radio-group
              v-model="radio.indate"
              style="margin-bottom: 20px"
              @change="indateChange"
            >
              <el-radio-button label="0">领券相对天数</el-radio-button>
              <el-radio-button label="1">指定绝对时间</el-radio-button>
            </el-radio-group>
            <el-input
              v-if="radio.indate == 0"
              v-model="addData.days"
              type="text"
              oninput="value=value.replace(/[^\d]/g,'')"
              maxlength="5"
            >
              <template #append>天</template>
            </el-input>
            <div v-if="radio.indate == 1">
              <el-form-item prop="gmtStart" style="display: inline-block">
                <el-date-picker
                  v-model="addData.gmtStart"
                  type="datetime"
                  placeholder="选择日期"
                  format="YYYY/MM/DD hh:mm:ss"
                  value-format="x"
                />
              </el-form-item>
              <span style="margin: 0px 1rem">至</span>
              <el-form-item prop="gmtEnd" style="display: inline-block">
                <el-date-picker
                  v-model="addData.gmtEnd"
                  type="datetime"
                  placeholder="选择日期"
                  format="YYYY/MM/DD hh:mm:ss"
                  value-format="x"
                />
              </el-form-item>
            </div>
          </el-form-item>
          <el-form-item label="商品限制范围">
            <el-radio-group v-model="radio.scope" @change="scopeChange">
              <el-radio-button label="0">全场通用</el-radio-button>
              <el-radio-button label="1">指定分类</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="优惠类目" v-if="radio.scope == 1">
            <el-cascader
              v-model="addData.categoryId"
              :props="props"
              placeholder="优惠类目"
              :options="categorytList"
              :show-all-levels="false"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span>
            <el-button @click="dialogShow = false">取消</el-button>
            <el-button type="primary" @click="submitForm(formRef)" v-if="!disabled"
              >确定</el-button
            >
          </span>
        </template>
      </el-dialog>
    </el-container>
    <el-footer>
      <!-- 分页组件 -->
      <ElPagination
        :total="pageInfo.total"
        :limit="pageInfo.limit"
        @changeReq="changeConfig"
      ></ElPagination>
    </el-footer>
  </div>
</template>

<script setup lang="ts">
import { post } from "@/request/http";
import { Search, Plus, Download } from "@element-plus/icons-vue";
import { exportExcel } from "@/utils/excel/generate";
import type { FormInstance } from "element-plus";
import { ref, reactive, onMounted, watch } from "vue";
import { ElMessage } from "element-plus";
let infoList = ref([]); //数据列表
let categorytList = ref([]); //类目列表
let title = ref(""); //弹出框title
let disabled = ref(false); //弹出框表单是否禁用
let dialogShow = ref(false); // 是否显示弹出框
const formRef = ref<FormInstance>(); //添加修改表单节点

// 请求表格数据的配置
let configReq: any = reactive({
  _gp: "admin.coupon",
  _mt: "list",
  title: "", //优惠卷标题
  type: null, //优惠券类型
  status: null, //优惠券状态
  limit: 20,
  pageNo: 1,
});
// 传给分页组件的数据
let pageInfo = reactive({
  limit: 20, //显示条数
  total: 0,
});
// 选择的数据
let options = reactive({
  type: [
    { value: 1, label: "满减券" },
    { value: 2, label: "立减券" },
    { value: "", label: "全部" },
  ],
  status: [
    { value: 0, label: "下架" },
    { value: 1, label: "正常" },
    { value: -1, label: "已过期" },
    { value: "", label: "全部" },
  ],
});

// 添加时传递的数据
let addData: any = reactive({
  _gp: "admin.coupon",
  _mt: "create",
  title: "", //标题
  type: 1, //类型
  description: "", //描述
  total: null, //总数
  limit: null, //限制领取
  discount: null, //优惠价格
  min: null, //满足优惠的最低价格
  status: 1, //状态
  categoryId: "", //优惠类别
  days: null, //优惠时长
  gmtStart: null, //开始时间
  gmtEnd: null, //结束时间
});
let validateTotal = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error("优惠券数量不能为空"));
  } else {
    if (addData.limit && value < +addData.limit) {
      callback(new Error("优惠券数不能小于每人限领"));
    }
    callback();
  }
};
let validateLimit = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error("请输入每人限领的数量"));
  } else {
    if (addData.total && value > +addData.total) {
      callback(new Error("每人限领不能大于优惠券数"));
    }
    callback();
  }
};
let validateDiscount = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error("优惠金额不能为空"));
  } else {
    if (addData.min && value > +addData.min) {
      callback(new Error("优惠金额不能大于最低消费金额"));
    }
    callback();
  }
};
let validateMin = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error("最低消费金额不能为空"));
  } else {
    console.log(value, addData.discount);
    if (addData.discount && value < +addData.discount) {
      callback(new Error("最低消费金额不能小于优惠金额"));
    }
    callback();
  }
};
let validategmtEnd = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error("请填写开始日期"));
  } else {
    if (addData.gmtStart && value < +addData.gmtStart) {
      callback(new Error("结束时间不能小于开始时间"));
    }
    callback();
  }
};
let validategmtStart = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error("请填写开始日期"));
  } else {
    // addData.gmtEnd不知道为什么addData.gmtEnd不是数字而是对象
    if (addData.gmtEnd && value > +addData.gmtEnd) {
      callback(new Error("开始时间不能大于结束时间"));
    }
    callback();
  }
};
const rules = reactive({
  title: [{ message: "优惠券名称不能为空", trigger: "blur", required: true }],
  type: [{ required: true }],
  description: [{ required: false }],
  total: [{ trigger: "blur", validator: validateTotal, required: true }],
  limit: [{ trigger: "blur", validator: validateLimit, required: true }],
  discount: [{ trigger: "blur", validator: validateDiscount, required: true }],
  min: [{ trigger: "blur", validator: validateMin, required: true }],
  status: [{ required: true }],
  gmtEnd: [
    { message: "请填写结束日期", trigger: "blur", required: true },
    { trigger: "change", validator: validategmtEnd },
  ],
  gmtStart: [
    { message: "请填写开始日期", trigger: "blur", required: true },
    { trigger: "change", validator: validategmtStart },
  ],
});

// 单选按钮
let radio = reactive({ indate: 0, scope: 0 });

// 类目级联选择器的配置
const props = reactive({
  label: "title",
  children: "childrenList",
  value: "id",
  emitPath: false,
  checkStrictly: true,
});

// 方法部分
// 获取类目数据的方法
const getCategoryt = () => {
  post({ _gp: "admin.category", _mt: "categoryTree" }).then((res) => {
    if (200 == res.errno) {
      //成功状态码
      // console.log(res.data);
      categorytList.value = res.data;
    }
  });
};
// 判断状态的函数
const switchStatus = (row: any): number => {
  let now = new Date().getTime(); //获取当前时间的时间戳
  //过期时
  if (row.gmtEnd && row.gmtEnd < now) return -1;
  // if (!row.gmtEnd && !row.days) return -1;
  //错误时
  if (row.status == 2) return 2;
  // 正常判断
  return row.status ? 1 : 0;
};
// 获取表格数据的方法
const getInfo = () => {
  post(configReq)
    .then((res) => {
      if (200 == res.errno) {
        //成功状态码
        // console.log(res.data)
        const data = res.data;
        infoList.value = data.items; //获取表格信息
        //判断状态
        for (const row of infoList.value) {
          (row as any).status = switchStatus(row);
        }
        pageInfo.total = data.total; //获取总条数
      }
    })
    .catch((err) => {
      console.log(err);
    });
};
// 改变
const indateChange = (e: any) => {
  if (e == 1) {
    addData.gmtStart = "";
    addData.gmtEnd = "";
  } else {
    addData.days = "";
  }
};
const scopeChange = () => {
  addData.categoryId = "";
};
// 分页切换触发
const changeConfig = (e: { page: number; limit: number }) => {
  Object.assign(configReq, { limit: e.limit, pageNo: e.page });
  getInfo();
};
//状态标签显示的内容
const switchDetails = (status: number) => {
  switch (status) {
    case 1:
      return "正常";
    case 0:
      return "下架";
    case -1:
      return "已过期";
  }
};
// 操作按钮的名字
const switchHandle = (status: number) => {
  switch (status) {
    case 1:
      return "冻结";
    case 0:
      return "激活";
    case -1:
      return "已过期";
  }
};

// 重置添加数据
const resetAddData = () => {
  Object.assign(addData, {
    _gp: "admin.coupon",
    _mt: "create",
    title: "",
    type: 1,
    description: "",
    total: null,
    limit: null,
    discount: null,
    min: null,
    status: 1,
    categoryId: "",
    days: null,
    gmtStart: null,
    gmtEnd: null,
  });
};

// 改变状态
const changeStatus = (row: any) => {
  let config = {
    _gp: "admin.coupon",
    _mt: "updateCouponStatus",
    id: row.id,
    status: 1,
  };
  switch (row.status) {
    case 1:
      config.status = 0;
      break;
    case 0:
      config.status = 1;
      break;
    case -1:
      ElMessage.error("过期优惠券，建议删除");
      return;
  }
  post(config)
    .then((res) => {
      if (200 == res.errno) {
        ElMessage.success("操作成功");
        getInfo();
      }
    })
    .catch((err) => {
      console.log(err);
    });
};

// 提交添加数据
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      let data = addData;
      post(data).then((res) => {
        if (200 == res.errno) {
          ElMessage.success("添加成功");
          dialogShow.value = false; //关闭弹窗
          getInfo(); //刷新数据
        }
      });
    }
  });
};

const lookInfo = (row: any) => {
  resetAddData();
  Object.assign(addData, row);
  disabled.value = true;
  title.value = "编辑";
  radio.indate = addData.days ? 0 : 1;
  radio.scope = addData.categoryId ? 1 : 0;
  dialogShow.value = true;
};
onMounted(() => {
  getInfo();
});
console.log(11);

watch(dialogShow, (n) => {
  if (categorytList.value.length != 0) return; //长度不为0时获取树
  if (n) getCategoryt();
});
</script>

//
<style scoped lang="less"></style>
